package com.example.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.DTO.UserDTO;
import com.example.common.Result;
import com.example.domain.Follow;
import com.example.mapper.FollowMapper;
import com.example.service.FollowService;
import com.example.service.UserService;
import com.example.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author chenliang
 * @description 针对表【tb_follow】的数据库操作Service实现
 * @createDate 2024-07-18 19:35:09
 */
@Service
@Slf4j
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow>
        implements FollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserService userService;

    /**
     * 关注和取消关注
     *
     * @param followUserId
     * @param isFollow
     * @return
     */
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        //1、获取登录用户
        Long userId = UserHolder.getUser().getId();
        String key = "follows:" + userId;
        //2、判断是关注还是取关
        if (isFollow) {
            //2.1、关注，则新增数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            boolean isSuccess = save(follow);
            if (isSuccess) {
                //把关注用户的id，放在Redis中的Set集合中
                stringRedisTemplate.opsForSet().add(key, followUserId.toString());
            }
            log.debug("用户关注成功，新增数据！");
        } else {
            //2.2、取关，则删除 delete from tb_follow where userId=? and follow_user_id=?
            QueryWrapper<Follow> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId).eq("follow_user_id", followUserId);
            boolean isSuccess = remove(queryWrapper);
            if (isSuccess) {
                //移除关注的用户Id
                stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
            }
            log.debug("用户取消关注成功，删除数据！");
        }
        return Result.ok();
    }

    /**
     * 判断是否关注
     *
     * @param followUserId
     * @return
     */
    @Override
    public Result isFollow(Long followUserId) {
        //1、获取登录用户
        Long userId = UserHolder.getUser().getId();
        //2、查询是否关注 select count(*) from tb_follow where userId=? and follow_user_id=?
        Integer count = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();
        //3、判断是否关注
        if (count <= 0) {
            return Result.ok("用户并未关注过");
        }
        return Result.ok("该博主已经关注过了！");
    }

    /**
     * 共同关注
     *
     * @param id
     * @return
     */
    @Override
    public Result followCommons(Long id) {
        //1、获取当前用户
        Long userId = UserHolder.getUser().getId();
        String key = "follows:" + userId;
        String key2 = "follows:" + id;
        //2、求交集
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key, key2);
        if (intersect == null || intersect.isEmpty()) {
            //无交集
            log.debug("用户共同关注为空！");
            return Result.ok(Collections.emptyList());
        }
        //3、解析id集合
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        //4、查询用户
        List<UserDTO> userDTOS = userService.listByIds(ids)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }
}




